package com.yun.algorithmproblem.leetcode;

import java.util.LinkedList;
import java.util.Queue;

public class Leetcode116 {
    public Node connect(Node root) {
        if(root==null){
            return null;
        }
        Queue<Node> queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size=queue.size();
            Node prev=queue.poll();
            offerNode(queue,prev);
            for (int i = 1; i < size; i++) {
                Node node=queue.poll();
                offerNode(queue,node);
                prev.next=node;
                prev=node;
            }
            prev.next=null;
        }
        return root;
    }

    private void offerNode(Queue<Node> queue,Node node){
        if(node.left!=null){
            queue.offer(node.left);
        }
        if(node.right!=null){
            queue.offer(node.right);
        }
    }
}
